package com.iot.blackip.startup;

import com.dc3.common.constant.CacheConstant;
import com.iot.blackip.dto.Dc3BlackIpDto;
import com.iot.blackip.events.CacheRefreshEvent;
import com.iot.blackip.service.BlackIpService;
import com.iot.openfeignblock.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 咕唧
 * @Date 2022/7/21 11:14
 * @Version 1.0
 */
@Component
public class LoadIp2Cache {

    private boolean isLoad;

    private BlackIpService blackIpService;

    private CacheClient cacheClient;

    private StreamBridge streamBridge;

    @Autowired
    public void setStreamBridge(StreamBridge streamBridge) {
        this.streamBridge = streamBridge;
    }

    @Autowired
    public void setCacheClient(CacheClient cacheClient) {
        this.cacheClient = cacheClient;
    }

    @Autowired
    public void setBlackIpService(BlackIpService blackIpService) {
        this.blackIpService = blackIpService;
    }

    /**
     * 监听程序是否启动
     * 查询黑名单所有ip放到缓存当中
     *
     * @param event
     */
    @EventListener
    public void onEvent(ContextRefreshedEvent event) {
        synchronized (cacheClient) {
            if (!isLoad) {
                isLoad = true;
                initData();
            }
        }
    }

    @EventListener
    public void onEvent(CacheRefreshEvent event) {
        initData();
    }

    private void initData() {
        List<Dc3BlackIpDto> allIp = blackIpService.findAllIp2Dto();
        //保存到redis缓存
        HashSet<String> keys = new HashSet<>();
        keys.add(CacheConstant.Entity.BLACK_IP);
        //先删除
        cacheClient.deleteKeys(keys);
        cacheClient.sAdd(CacheConstant.Entity.BLACK_IP, allIp.stream().map(Dc3BlackIpDto::getIp).collect(Collectors.toSet()));

        //发送消息，通知网关缓存更新了
        streamBridge.send("blackipchange", "blackipchange");
    }
}
